from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import Dict, Any, List
import json
from datetime import datetime, timedelta

from database import get_db, DataRecord, DataSource
from services.cache_service import CacheService, CacheKeys
from services.ai_service import ai_service

router = APIRouter()

@router.get("/")
async def get_dashboard_data(db: Session = Depends(get_db)):
    """获取仪表盘数据"""
    try:
        # 尝试从缓存获取数据
        cache_key = CacheKeys.dashboard_data_key("overview")
        cached_data = await CacheService.get(cache_key)
        
        if cached_data:
            return {
                "success": True,
                "data": cached_data,
                "source": "cache",
                "timestamp": datetime.now().isoformat()
            }
        
        # 从数据库获取最新数据
        dashboard_data = {}
        
        # 获取各种数据源的最新数据
        data_sources = db.query(DataSource).filter(DataSource.is_active == True).all()
        
        for source in data_sources:
            latest_record = db.query(DataRecord).filter(
                DataRecord.source_id == source.id
            ).order_by(DataRecord.timestamp.desc()).first()
            
            if latest_record:
                try:
                    data = json.loads(latest_record.data_json)
                    dashboard_data[source.data_type] = {
                        "data": data,
                        "last_updated": latest_record.timestamp.isoformat(),
                        "source_name": source.name
                    }
                except json.JSONDecodeError:
                    continue
        
        # 缓存数据
        await CacheService.set(cache_key, dashboard_data, expire=300)  # 5分钟缓存
        
        return {
            "success": True,
            "data": dashboard_data,
            "source": "database",
            "timestamp": datetime.now().isoformat()
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取仪表盘数据失败: {str(e)}")

@router.get("/data/{data_type}")
async def get_data_by_type(data_type: str, db: Session = Depends(get_db)):
    """根据数据类型获取数据"""
    try:
        # 检查缓存
        cache_key = CacheKeys.dashboard_data_key(data_type)
        cached_data = await CacheService.get(cache_key)
        
        if cached_data:
            return {
                "success": True,
                "data": cached_data,
                "source": "cache"
            }
        
        # 从数据库获取数据
        source = db.query(DataSource).filter(
            DataSource.data_type == data_type,
            DataSource.is_active == True
        ).first()
        
        if not source:
            raise HTTPException(status_code=404, detail=f"未找到数据类型: {data_type}")
        
        # 获取最近7天的数据
        seven_days_ago = datetime.now() - timedelta(days=7)
        records = db.query(DataRecord).filter(
            DataRecord.source_id == source.id,
            DataRecord.timestamp >= seven_days_ago
        ).order_by(DataRecord.timestamp.asc()).all()
        
        data = []
        for record in records:
            try:
                record_data = json.loads(record.data_json)
                data.append({
                    "timestamp": record.timestamp.isoformat(),
                    "data": record_data
                })
            except json.JSONDecodeError:
                continue
        
        result = {
            "data_type": data_type,
            "source_name": source.name,
            "records": data,
            "total_records": len(data)
        }
        
        # 缓存数据
        await CacheService.set(cache_key, result, expire=600)  # 10分钟缓存
        
        return {
            "success": True,
            "data": result,
            "source": "database"
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取数据失败: {str(e)}")

@router.get("/insights")
async def get_dashboard_insights(db: Session = Depends(get_db)):
    """获取仪表盘洞察"""
    try:
        # 获取仪表盘数据
        dashboard_response = await get_dashboard_data(db)
        dashboard_data = dashboard_response["data"]
        
        # 使用AI生成洞察
        insights = await ai_service.generate_dashboard_insights(dashboard_data)
        
        return {
            "success": True,
            "insights": insights,
            "timestamp": datetime.now().isoformat()
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"生成洞察失败: {str(e)}")

@router.get("/stats")
async def get_dashboard_stats(db: Session = Depends(get_db)):
    """获取仪表盘统计信息"""
    try:
        # 数据源统计
        total_sources = db.query(DataSource).count()
        active_sources = db.query(DataSource).filter(DataSource.is_active == True).count()
        
        # 数据记录统计
        total_records = db.query(DataRecord).count()
        today_records = db.query(DataRecord).filter(
            DataRecord.timestamp >= datetime.now().date()
        ).count()
        
        # 最近24小时的数据更新情况
        yesterday = datetime.now() - timedelta(days=1)
        recent_records = db.query(DataRecord).filter(
            DataRecord.timestamp >= yesterday
        ).all()
        
        # 按数据类型统计
        data_type_stats = {}
        for record in recent_records:
            source = db.query(DataSource).filter(DataSource.id == record.source_id).first()
            if source:
                data_type = source.data_type
                if data_type not in data_type_stats:
                    data_type_stats[data_type] = 0
                data_type_stats[data_type] += 1
        
        stats = {
            "data_sources": {
                "total": total_sources,
                "active": active_sources,
                "inactive": total_sources - active_sources
            },
            "data_records": {
                "total": total_records,
                "today": today_records,
                "last_24h": len(recent_records)
            },
            "data_type_distribution": data_type_stats,
            "last_updated": datetime.now().isoformat()
        }
        
        return {
            "success": True,
            "stats": stats
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取统计信息失败: {str(e)}")
